package org.grc.app.z_project.z_framework.util;

import org.codehaus.jackson.map.ObjectMapper;

/** 
 * JSON 操作工具类
 *  
 * @author grc
 * @since 1.0-SNAPSHOT
 */
public class JsonUtil {

	private static final ObjectMapper objectMapper = new ObjectMapper();

	/** 
	 * 将 Java 对象转为 JSON 字符串
	 */
	public static <T> String toJSON(T obj) {
		String jsonStr = null;
		try {
			jsonStr = objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}

    /**
     * <p>将 JSON 字符串转为 Java 对象</P>
     * 
     * <p>*注* : 被转换的类必须为 <b>public</b> </P> 
     */
	public static <T> T fromJSON(String jsonStr, Class<T> type) {
		T obj = null;
		try {
			obj = objectMapper.readValue(jsonStr, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
